package com.zz.zjc.config;

import com.zz.zjc.model.ExceptionLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

@Aspect
@Component
public class ExceptionLogAspectConfig {

    Logger logger = LoggerFactory.getLogger(getClass());
    @Pointcut("execution(public * com.zz.zjc.controller..*.*(..))")
    public void Pointcut() {
    }

   /* //前置通知
    @Before("Pointcut()")
    public void beforeMethod(JoinPoint joinPoint){

    }

    //@After: 后置通知
    @After("Pointcut()")
    public void afterMethod(JoinPoint joinPoint){

    }

    //@AfterRunning: 返回通知 rsult为返回内容
    @AfterReturning(value="Pointcut()",returning="result")
    public void afterReturningMethod(JoinPoint joinPoint,Object result){

    }*/

    //@AfterThrowing: 异常通知
    @AfterThrowing(value="Pointcut()",throwing="e")
    public void afterReturningMethod(JoinPoint joinPoint, Exception e){
        try {
            ExceptionLog exceptionLog = new ExceptionLog();
            exceptionLog.setException(e.getClass().getName());
            exceptionLog.setClassName(joinPoint.getTarget().getClass().getName());
            exceptionLog.setArgs(Arrays.asList(joinPoint.getArgs()).toString());
            exceptionLog.setMethodName(joinPoint.getSignature().getName());
            StackTraceElement[] es = e.getStackTrace();
            String err = e.toString()+"\r\n";
            for (StackTraceElement stackTraceElement : es) {
                err += stackTraceElement.toString()+"\r\n";
            }
            exceptionLog.setText(err);
            exceptionLog.setCreateTime(new Date());
        }catch (Exception e1){
            logger.info(e1.getMessage());
        }

    }

    //@Around：环绕通知
   /* @Around("Pointcut()")
    public Object AroundMethod(ProceedingJoinPoint pjp) throws Throwable {
        Object object = pjp.proceed();
        return object;
    }*/
}
